package com.example.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.example.springboot.controller.dto.PestDTO;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.controller.request.PestPageRequest;
import com.example.springboot.controller.request.SavePestRequest;
import com.example.springboot.entity.Pest;
import com.example.springboot.entity.PestImage;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.PestImageMapper;
import com.example.springboot.mapper.PestMapper;
import com.example.springboot.service.IPestService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PestService implements IPestService {

    @Resource
    private PestMapper pestMapper;

    @Autowired
    private PestImageMapper pestImageMapper;

    @Autowired
    private PestImageService pestImageService;

    /**
     * 获取所有虫害信息
     *
     * @return 虫害信息列表
     */
    @Override
    public List<Pest> list() {
        return pestMapper.list();
    }

    /**
     * 分页查询
     *
     * @param baseRequest 请求参数
     * @return 分页结果
     */
    @Override
    public PageInfo<Pest> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        return new PageInfo<>(pestMapper.listByCondition(baseRequest));
    }


    @Override
    public PageInfo<PestDTO> pageWithCover(PestPageRequest req) {

        // 1. 普通分页
        PageInfo<Pest> page = PageHelper.startPage(req.getPageNum(), req.getPageSize())
                .doSelectPageInfo(() -> pestMapper.listByCondition(req));

        // 2. 把 Pest -> PestDTO，并补全图片
        List<PestDTO> dtoList = page.getList()
                .stream()
                .map(p -> {
                    PestDTO dto = new PestDTO();
                    BeanUtils.copyProperties(p, dto);
                    dto.setCover(pestImageService.getByPestId(p.getId()));
                    return dto;
                })
                .collect(Collectors.toList());

        // 3. 用 DTO 列表重新包装分页信息
        PageInfo<PestDTO> dtoPage = new PageInfo<>();
        BeanUtils.copyProperties(page, dtoPage);
        dtoPage.setList(dtoList);
        return dtoPage;
    }


    /**
     * 保存虫害信息并返回id(作为pest_id关联图片)
     * @param obj
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer save(SavePestRequest obj) {
        try {
            Pest pest = new Pest();
            pest.setCreateTime(LocalDate.now());
            pest.setUpdateTime(LocalDate.now());
            pest.setCategory(category(obj.getCategories()));
            BeanUtils.copyProperties(obj, pest);
            pestMapper.save(pest); // 插入后应能获取生成的 ID
            return pest.getId(); // 返回生成的 pestId
        } catch (Exception e) {
            throw new ServiceException("数据插入错误", e);
        }
    }

    /**
     * 根据id获取虫害信息
     *
     * @param id id
     * @return 虫害信息
     */
    @Override
    public Pest getById(Integer id) {
        return pestMapper.getById(id);
    }
    /**
     * 更新虫害信息
     *
     * @param obj obj
     */
    @Override
    public void update(SavePestRequest obj) {
        try {
            Pest pest = new Pest();
            pest.setCategory(category(obj.getCategories()));
            pest.setUpdateTime(LocalDate.now());
            BeanUtils.copyProperties(obj, pest);
            pestMapper.updateById(pest);
        } catch (Exception e) {
            throw new ServiceException("数据更新错误", e);
        }

    }
    /**
     * 批量删除虫害并将关联图片删除
     *
     * @param id id
     */
    @Override
    public void deleteById(Integer id) {
        // 先删除图片
        pestImageMapper.deleteByPestId(id);
        // 再删除虫害
        pestMapper.deleteById(id);
    }

    /**
     * 获取分类category的名称（由categories拼接而成）
     *
     * @param categories 分类列表
     * @return 分类名称
     */
    private String category(List<String> categories) {
        StringBuilder sb = new StringBuilder();
        if (CollUtil.isNotEmpty(categories)) {
            categories.forEach(v -> sb.append(v).append(" > "));
            return sb.substring(0, sb.lastIndexOf(" > "));
        }
        return sb.toString();
    }



}
